// 封装个人信息相关的请求

import { ApiRes, User, UserProfile } from '@/types/data'
import { RootAction, RootThunkAction } from '@/types/store'
import http from '@/utils/request'
import { removeToken } from '@/utils/token'

// 获取用户基本资料
export function getUser(): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiRes<User>>('/user')
    // console.log(res.data.data)

    dispatch({
      type: 'profile/set_user',
      payload: res.data.data,
    } as RootAction)
  }
}

// 获取用户详情
export function getUserProfile(): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiRes<UserProfile>>('/user/profile')
    // console.log(res.data.data)

    dispatch({
      type: 'profile/set_user_profile',
      payload: res.data.data,
    } as RootAction)
  }
}

// Partial<T> 将一个已知的类型每个属性都变为可选的
// ReturnType<T> 得到一个函数类型的返回值类型
export function updateUserProfile(data: Partial<UserProfile>): RootThunkAction {
  return async (dispatch) => {
    // data { name: 'zs' }    { intro: '不错' }  { gender: 0 } { birthday: '2022-09-06' }
    // 更新
    await http.patch('/user/profile', data)

    // 重新获取新的用户详情
    await dispatch(getUserProfile())
  }
}

export function updateUserPhoto(data: FormData): RootThunkAction {
  return async (dispatch) => {
    // 更新用户头像
    await http.patch('/user/photo', data)

    // 重新获取用户详情
    await dispatch(getUserProfile())
  }
}

export function logout(): RootThunkAction {
  return async (dispatch) => {
    // 清除token（仓库 本地） 基本资料 详情资料
    removeToken()

    dispatch({
      type: 'login/login',
      payload: {},
    } as RootAction)

    dispatch({
      type: 'profile/set_user',
      payload: {},
    } as RootAction)

    dispatch({
      type: 'profile/set_user_profile',
      payload: {},
    } as RootAction)
  }
}
